package org.spi.animal;

import org.spi.animal.spi.ShowYourselfProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @Author czl
 * @Date 2024-04-28
 */
public class ServiceLoaderUtil {
    public static List<ShowYourselfProvider> providers() {
        // 1.创建 List 集合，用于存储 ShowYourselfProvider 接口的所有实现类
        List<ShowYourselfProvider> servicesList = new ArrayList<>();

        // 2.基于 SPI 加载所有 ShowYourselfProvider 接口的实现
        ServiceLoader<ShowYourselfProvider> loader =
                ServiceLoader.load(ShowYourselfProvider.class);

        // 3.循环遍历 ServiceLoader，读取所有 ShowYourselfProvider 接口的实现类，添加到 List 集合中
        // void accept(T t);
        loader.forEach(providerImpl -> servicesList.add(providerImpl));

        // 4.返回 List 集合
        return servicesList;
    }
}
